package com.demo.app.config.exception;

import enums.ErrorCodeEnum;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import result.Result;

import java.nio.file.AccessDeniedException;
import java.security.SignatureException;


/**
 * @program: fire_control
 * @description: 处理自定义的业务异常
 * @author: fbl
 * @create: 2021-01-15 16:21
 **/
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * token过期
     *
     * @return
     */
    @ExceptionHandler(value = {ExpiredJwtException.class})
    @ResponseBody
    public Result expiredJwtException() {
        return Result.failure(ErrorCodeEnum.SYS_ERR_TOKEN_SIGNATURE);
    }

    /**
     * token错误
     *
     * @return
     */
    @ExceptionHandler(value = SignatureException.class)
    @ResponseBody
    public Result signatureException() {
        return Result.failure(ErrorCodeEnum.SYS_ERR_TOKEN_SIGNATURE);
    }

    /**
     * 没有权限
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = AccessDeniedException.class)
    public Result handleAuthorizationException(AccessDeniedException e) {
        return Result.failure(200,"没有权限，请联系管理员授权");
    }

    /**
     * 重复提交
     *
     * @return
     */
    @ExceptionHandler(value = RepetitionSubmitException.class)
    @ResponseBody
    public Result repetitionSubmitException() {
        return Result.failure(ErrorCodeEnum.SYS_ERR_REPETITION_SUBMIT);
    }

    /**
     * 账号或密码错误
     *
     * @return
     */
    @ExceptionHandler(value = UserPasswordNotMatchException.class)
    @ResponseBody
    public Result userPasswordNotMatchException() {
        return Result.failure(ErrorCodeEnum.SYS_ERR_LOGIN_FAIL);
    }

    /**
     * 参数校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result validationExceptionHandler(MethodArgumentNotValidException e){
        String defaultMessage = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return Result.failure(400,defaultMessage);
    }

}
